/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2021 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "adc.h"
#include "spi.h"
#include "tim.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "nrf24l01.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
uint32_t now_ms;

uint8_t rx_buf[32];
uint32_t rx_count=0;
uint32_t tx_count = 0;
uint32_t rx_framerate=0;

int rf_ch_index=0;
int rf_channel = 0;
int rf_tim_flag=0;
int receive_lost_count=0;

#define SYS_STATE_WAIT  0
#define SYS_STATE_WORK  1
int sys_state=SYS_STATE_WAIT;

int wait_times  = 0;

uint32_t receive_time=0;
uint32_t receive_time_lase=0;
uint32_t receive_interval=0;
uint32_t change_finish_time=0;
uint32_t change_finish_time_last=0;
uint32_t change_finish_interval=0;

int rf_irq_flag=0;

uint16_t channel_value[8];
uint16_t pwm_value[8];
/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
void led_on(uint8_t n)
{
    if(n==LED_RED)
    {
        HAL_GPIO_WritePin(LED1_GPIO_Port,LED1_Pin,GPIO_PIN_RESET); 
    }
    else
    {
        HAL_GPIO_WritePin(LED2_GPIO_Port,LED2_Pin,GPIO_PIN_RESET);        
    }
}
    
void led_off(uint8_t n)
{
    if(n==LED_RED)
    {
        HAL_GPIO_WritePin(LED1_GPIO_Port,LED1_Pin,GPIO_PIN_SET); 
    }
    else
    {
        HAL_GPIO_WritePin(LED2_GPIO_Port,LED2_Pin,GPIO_PIN_SET);        
    }
}

void led_control(uint8_t n)
{
    if(n&LED_RED) {
        HAL_GPIO_WritePin(LED1_GPIO_Port,LED1_Pin,GPIO_PIN_RESET); 
    }
    else  {
        HAL_GPIO_WritePin(LED1_GPIO_Port,LED1_Pin,GPIO_PIN_SET); 
    }
    
    if(n&LED_BLUE) {
        HAL_GPIO_WritePin(LED2_GPIO_Port,LED2_Pin,GPIO_PIN_RESET); 
    }
    else  {
        HAL_GPIO_WritePin(LED2_GPIO_Port,LED2_Pin,GPIO_PIN_SET); 
    }
}

void start_timer_pwm(void)
{
    TIM1->CCR1 = 1500;
    TIM1->CCR2 = 1500;
    TIM1->CCR3 = 1500;
    TIM1->CCR4 = 1500;
    HAL_TIM_PWM_Start(&htim1,TIM_CHANNEL_1);
    HAL_TIM_PWM_Start(&htim1,TIM_CHANNEL_2);
    HAL_TIM_PWM_Start(&htim1,TIM_CHANNEL_3);
    HAL_TIM_PWM_Start(&htim1,TIM_CHANNEL_4);
    
    TIM3->CCR1 = 1500;
    TIM3->CCR2 = 1500;
    TIM3->CCR3 = 1500;
    TIM3->CCR4 = 1500;
    HAL_TIM_PWM_Start(&htim3,TIM_CHANNEL_1);
    HAL_TIM_PWM_Start(&htim3,TIM_CHANNEL_2);
    HAL_TIM_PWM_Start(&htim3,TIM_CHANNEL_3);
    HAL_TIM_PWM_Start(&htim3,TIM_CHANNEL_4);
}

void change_rf_channel(void)
{
    rf_ch_index++;
    if(rf_ch_index>=10)
    {
        rf_ch_index = 0;
    }
    
    rf_channel = (rf_ch_index *5) + 1;
}

void tim17_init(void)
{
    __HAL_RCC_TIM17_CLK_ENABLE();
    
    TIM17->PSC = 63;
    TIM17->ARR = 65535;
    TIM17->CR1 = 0x01;
}
    
void update_channel_value(void)
{
    int i;
    
    for(i=0;i<8;i++)
    {
        channel_value[i] = (rx_buf[4 + (i*2)]<<8) | (rx_buf[5 + (i*2)]);
    }
    
    TIM1->CCR1 = channel_value[4];
    TIM1->CCR2 = channel_value[3];
    TIM1->CCR3 = channel_value[1];
    TIM1->CCR4 = channel_value[0];//CH1
    
    TIM3->CCR1 = channel_value[2];
    TIM3->CCR2 = channel_value[7];
    TIM3->CCR3 = channel_value[6];
    TIM3->CCR4 = channel_value[5];
}
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
    uint8_t nrf_check;
    uint8_t rf_sta;

    HAL_Init();

    SystemClock_Config();

    MX_GPIO_Init();
    MX_ADC1_Init();
    MX_SPI1_Init();
    MX_TIM1_Init();
    MX_TIM3_Init();
    MX_TIM14_Init();
    
    start_timer_pwm();
    
    TIM14->ARR = 2500;
    TIM14->PSC = 63;
    HAL_TIM_Base_Start_IT(&htim14);
    
    NRF24L01_Init();

    HAL_Delay(100);
    
    NRF24L01_Check();
    nrf_check = NRF24L01_Check();
    if(nrf_check)
    {
        led_control(LED_RED);
        while(1);
    }
    else
    {
        led_control(LED_BLUE);
    }
        
    while (1)
    {
        switch(sys_state)
        {
            case SYS_STATE_WAIT:    //配对模式
                led_control(LED_RED);
            
                if(rf_tim_flag)     //每隔22ms换频率 一共10个频率
                {
                    rf_tim_flag = 0;
                    
                    change_rf_channel();
                    NRF24L01_RX_Mode(rf_channel);
                }
                
                if(0==NRF24L01_RxPacket(rx_buf))    //收到数据后切换到工作模式
                {
                    rx_count++;
                    tx_count = (rx_buf[0]<<8) | rx_buf[1];
                    led_control(LED_BLUE);
                    
                    change_rf_channel();
                    NRF24L01_RX_Mode(rf_channel);
                    
                    __HAL_TIM_DISABLE(&htim14);
                    TIM14->CNT = 0;
                    __HAL_TIM_ENABLE(&htim14);
                    
                    sys_state = SYS_STATE_WORK;
                }
                break;
            case SYS_STATE_WORK:    //工作模式
                led_control(LED_BLUE);
            
                if(rf_irq_flag)
                {
                    rf_irq_flag = 0;

                    __HAL_TIM_DISABLE(&htim14);//停止定时器
                    
                    rf_sta = NRF24L01_Read_Reg(STATUS);                                        
                    if(rf_sta & RX_OK)
                    {                                                
                        NRF24L01_Read_Buf(RD_RX_PLOAD,rx_buf,RX_PLOAD_WIDTH);//读取数据
                        NRF24L01_Write_Reg(FLUSH_RX,0xff);//清除RX FIFO寄存器 
                        
                        rx_count++;
                        tx_count = (rx_buf[0]<<8) | rx_buf[1];
                        led_control(LED_BLUE);
                        
                        update_channel_value();
                        
                        /*收到数据立刻切换到下一个频率*/
                        change_rf_channel();
                        NRF24L01_RX_Mode(rf_channel);
                        
                        TIM14->CNT = 0;
                        __HAL_TIM_ENABLE(&htim14);
                    }
                    NRF24L01_Write_Reg(WRITE_REG_NRF+STATUS,rf_sta); //清除TX_DS或MAX_RT中断标志                                        
                }
                
                if(rf_tim_flag)//switch the frequent when the timer is update 
                {
                    rf_tim_flag = 0;
                    receive_lost_count++;
                    if(receive_lost_count>5)
                    {
                        receive_lost_count = 0;
                        sys_state = SYS_STATE_WAIT;
                        wait_times++;
                        TIM14->ARR = 5000;
                    }
                    change_rf_channel();
                    NRF24L01_RX_Mode(rf_channel);
                }
                break;
        }
        
        led_control(0);
    }
}

uint32_t tim14_framerate=0;
uint32_t tim14_irq_count=0;

void main_tick_callback(void)
{
    static int count=0;
    static uint32_t rx_count_last = 0;
    
    now_ms++;
    
    count++;
    if(count>=1000)
    {
        count = 0;
        
        rx_framerate = rx_count - rx_count_last;
        rx_count_last = rx_count;
        
        tim14_framerate = tim14_irq_count;
        tim14_irq_count = 0;
    }
}



void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
    if(htim->Instance == TIM14)
    {
        rf_tim_flag = 1;
        tim14_irq_count++;
    }
}

void HAL_GPIO_EXTI_Falling_Callback(uint16_t GPIO_Pin)
{
    if(GPIO_Pin == RF_IRQ_Pin)
    {
        rf_irq_flag = 1;
    }
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
  RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};

  /** Configure the main internal regulator output voltage
  */
  HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1);
  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSIDiv = RCC_HSI_DIV1;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
  RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV1;
  RCC_OscInitStruct.PLL.PLLN = 8;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
  /** Initializes the peripherals clocks
  */
  PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USART1|RCC_PERIPHCLK_ADC;
  PeriphClkInit.Usart1ClockSelection = RCC_USART1CLKSOURCE_PCLK1;
  PeriphClkInit.AdcClockSelection = RCC_ADCCLKSOURCE_SYSCLK;
  if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
